package com.haoliangtian.ui.login;

import android.app.Activity;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.haoliangtian.R;
import com.haoliangtian.bean.LoginResponse;
import com.haoliangtian.ui.login.LoginViewModel;
import com.haoliangtian.ui.login.LoginViewModelFactory;
import com.haoliangtian.utils.SharedPreferencesUtil;

public class LoginActivity extends AppCompatActivity {
    //LoginActivity的ViewModel
    private LoginViewModel loginViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //获取LoginActivity的ViewModel
        loginViewModel = ViewModelProviders.of(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);

        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);
        final Button loginButton = findViewById(R.id.login);
        final ProgressBar loadingProgressBar = findViewById(R.id.loading);
        //监听登录数据变化
        loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    return;
                }
                //登录按钮可用
                loginButton.setEnabled(loginFormState.isDataValid());

                //用户名错误
                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError(getString(loginFormState.getUsernameError()));
                }
                //密码错误
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(loginFormState.getPasswordError()));
                }
            }
        });
        //监听登录结果
        loginViewModel.getLoginResult().observe(this, new Observer<LoginResponse>() {
            @Override
            public void onChanged(@Nullable LoginResponse loginResult) {
                if (loginResult == null) {
                    return;
                }
                //隐藏进度条
                loadingProgressBar.setVisibility(View.GONE);
                //登录失败
                if (!loginResult.isSuccess()) {
                    showLoginFailed("登录失败，请重新登录");
                }
                //登录成功
                if (loginResult.isSuccess()) {
                    updateUiWithUser("登录成功");
                    SharedPreferencesUtil.getInstance(getBaseContext())
                            .setParam(getString(R.string.user_name), loginResult.getSessMap().getYhjbxx().getYhm() + "")
                            .setParam(getString(R.string.user_password), loginResult.getSessMap().getYhjbxx().getYhmm() + "")
                            .setParam(getString(R.string.user_identity), loginResult.getSessMap().getYhjbxx().getYhxm() + "")
                            .setParam(getString(R.string.user_company), loginResult.getSessMap().getYhjbxx().getDwmc() + "")
                            .setParam(getString(R.string.user_login), loginResult.getSessMap().getYhjbxx().getId() + "");
                }
                setResult(Activity.RESULT_OK);
                //一旦登录成功，关闭登录页面
                finish();


            }
        });
        //监听文本框
        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                //更新用户名和密码
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        //输入完密码后，点击完成，去登陆
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    //开始登录
                    loginViewModel.login(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString());
                }
                return false;
            }
        });
        //点击登录按钮
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示进度条
                loadingProgressBar.setVisibility(View.VISIBLE);
                //开始登录
                loginViewModel.login(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        });
    }

    /**
     * 提示登录成功
     */
    private void updateUiWithUser(String message) {
        // TODO : initiate successful logged in experience
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }

    /**
     * 提示登录失败
     *
     * @param errorString
     */
    private void showLoginFailed(String errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }
}
